package com.example.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.common.constant.CartConstant;
import com.example.common.utils.R;
import com.example.gulimall.cart.feign.ProductFeignService;
import com.example.gulimall.cart.interceptor.CartInterceptor;
import com.example.gulimall.cart.service.CartService;
import com.example.gulimall.cart.to.UserInfoTo;
import com.example.gulimall.cart.vo.CartItemVo;
import com.example.gulimall.cart.vo.CartVo;
import com.example.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.example.common.constant.CartConstant.CART_PREFIX;

@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;


    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        // 商品添加到购物车

        String result = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(result)){
            // redis购物车没有改商品
            CartItemVo cartItemVo = new CartItemVo();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //远程查询当前要添加的商品信息
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(data.getSkuDefaultImg());
                cartItemVo.setTitle(data.getSkuTitle());
                cartItemVo.setSkuId(skuId);
                cartItemVo.setPrice(data.getPrice());
            }, executor);



            //2 远程查询商品的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValue = productFeignService.getSkuSaleAttrValue(skuId);

                cartItemVo.setSkuAttrValues(skuSaleAttrValue);
            }, executor);
            //等两个异步任务执行完再保存到redis
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();
            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),s);
            return cartItemVo;
        }else{
            //redis 购物车已经有该商品
            CartItemVo itemVo = JSON.parseObject(result, CartItemVo.class);
            itemVo.setCount(itemVo.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(itemVo));
            return itemVo;
        }



    }

    /**
     * 获取购物车的某个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String)cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(o, CartItemVo.class);
        return cartItemVo;

    }

    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        // 1区分登录没有
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            //1 登录
            //登录后的购物车键
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //临时购物车的键
            String tempCartKey=CART_PREFIX + userInfoTo.getUserKey();
            BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(cartKey);
            //如果临时购物车的数据还没进行合并，合并购物车
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems!=null&&tempCartItems.size()>0){
                //如果临时购物车有数据，将临时购物车合并到用户购物车
                for (CartItemVo tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                //清除临时购物车数据
                clearCart(tempCartKey);
            }
            //3  获取登录后的购物车(包含合并过来的临时购物车数据和登录后的购物车数据)

            List<CartItemVo>  cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);

        }else {
            // 2 没登陆
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的所有购物项
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        }
        return  cartVo;
    }


    /**
     * 获取到我们要操作的购物车
     * @return
     */

    private   BoundHashOperations<String, Object, Object>  getCartOps() {
        //1 得到用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey="";
        if (userInfoTo.getUserId()!=null){
            //说明用户登录了
            cartKey= CART_PREFIX+userInfoTo.getUserId();
        }else {
            //用户没登陆，临时购物车
            cartKey= CART_PREFIX+userInfoTo.getUserKey();
        }
        //2 判断当前购物车是否已经有该商品
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return  operations;
    }
    private  List<CartItemVo> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOperations.values();
        if (values!=null&&values.size()>0){
            List<CartItemVo> collect = values.stream().map(value -> {
                String str = (String) value;
                CartItemVo cartItemVo= JSON.parseObject(str,CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
          return collect;
        }
        return null;
    }

    /**
     * 清空购物车
     * @param cartKey
     */
    @Override
    public void  clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    /**
     * 勾选购物项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    /**
     * 改变购物车数量
     * @param skuId
     * @param num
     */
    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItemVo> getUserCartItems() {

        //获取用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //判断是否登录
        if (userInfoTo.getUserId()==null){
            return  null;
        }else {
            //获取用户key
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //查询当前用户的购物车信息
            List<CartItemVo> cartItems = getCartItems(cartKey);
            // 过滤出购物车里选中的购物项
            List<CartItemVo> collect = cartItems.stream()
                    .filter(item -> item.getCheck())
                    .map(item->{
                        //TODO 1 更新最新价格，因为购物车可能是很久之前添加的，现在再来下单，
                        // 价格已经发生了变换，所有要查询最新的价格

                        BigDecimal price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(price);
                        return item;
                    }).collect(Collectors.toList());
            return  collect;
        }


    }

}
